<template>
  <view class="box-list-module">
    <!-- 遮罩层 -->
    <view class="popup" @click="onClickOperate($event, 'close', {})"> </view>
    <view class="box-module">
      <!-- 头部 -->
      <view class="top">
        <view class="title"
          >全部盒子

          <view
            class="switch-type"
            :class="checkNoneClass"
            @tap="onClickOperate($event, 'changeOpen', {})"
          >
            <view class="type-group" :class="checkNoneClass">
              <text v-if="checkNoneClass != 'open'">看空箱</text>
              <view class="round"></view>
            </view>

            <view class="none"> 看空箱 </view>
          </view>
        </view>
        <img
          class="close-icon"
          src="../img/back-1.png"
          alt=""
          @click="onClickOperate($event, 'close', {})"
        />
      </view>
      <!-- 选项卡 -->
      <view class="tabs" v-if="total > threshold">
        <view
          class="tab-item"
          :class="active == index ? 'active' : ''"
          v-for="(item, index) in tabList"
          :key="index"
          @click="onClickOperate($event, 'changeActive', { item, index })"
        >
          {{ item.label }}
        </view>
      </view>
      <!-- 箱子列表         :scroll-left="scrollTop"-->
      <scroll-view
        class="content"
        scroll-y
        :scroll-with-animation="true"
        :scroll-top="scrollTop"
        @scroll="onScroll"
        @scrolltolower="onreachBottom"
      >
        <view class="box-list">
          <block v-for="(item, index) in list" :key="index">
            <view :hidden="!checkNone && item.status == 2">
              <box-item
                @tap="onClickOperate($event, 'select', { item, index })"
                :index="index"
                :details="item"
              ></box-item>
            </view>
          </block>
        </view>
      </scroll-view>
    </view>
  </view>
</template>
<script>
/**
 * 箱子列表
 * @property {String|Number} total 箱子总数
 * @property {String|Number} rows 当前箱子可展示区间数
 * @method changeBoxListMod 关闭弹窗
 * @method select 选择箱子
 * @method changeActive 选择区间
 *
 */

import tools from '@/shopro/utils/tools';
import BoxItem from './live-box-item.vue';
const _delay = tools.delayDither(100);
export default {
  // 建议 创建每个组件时 都添加name属性 标识组件名称
  name: 'boxList',
  components: { BoxItem },
  props: {
    initiallyId: {
      type: [String, Number],
      default: '1',
    },
    total: {
      type: [String, Number],
      default: 0,
    },
    // 当前箱子
    currentBox: {
      type: Object,
      default: () => ({}),
    },
    // 区间可展示数
    rows: {
      type: [String, Number],
      default: 4,
    },
  },
  data() {
    return {
      // 切换 动画 类名 查看空箱按钮
      checkNoneClass: 'open',
      // 当前 滚动条 位置
      oldScrollTop: 10,
      scrollTop: 0,
      active: 0,
      //弹窗状态
      open: true,
      // 看空箱
      checkNone: true,
      // 列表
      list: [],
    };
  },
  // 计算属性 适配者模式
  computed: {
    /**
     * 箱子范围区间
     * 显示文字
     * label: 1-20
     * 区间内箱子总数
     * value: 20
     */
    tabList() {
      return this.initList();
    },
    // 当前 箱子号
    currentIndex() {
      return this.currentBox.index;
    },
    //可显示阈值
    threshold() {
      return this.rows + 4;
    },
  },
  // 数据监听
  watch: {},
  /**
   * 生命周期 类似 发布订阅者模式
   */
  //监听页面初始化，其参数同 onLoad 参数 触发时机早于 onLoad 百度小程序
  //onInit() {},
  mounted() {
    this.open = true;
    this.firstInitData();
  },
  /** 监听页面加载
   * 其参数为上个页面传递的数据，
   * 参数类型为 Object（用于页面传参）
   */
  onLoad() {},
  // 监听页面显示。页面每次出现在屏幕上都触发 包括从下级页面点返回露出当前页面
  onShow() {},
  // 监听页面初次渲染完成 注意如果渲染速度快，会在页面进入动画完成前触发
  onReady() {},
  // 监听页面隐藏
  onHide() {},
  // 监听页面卸载
  onUnload() {},
  methods: {
    /**
     *  页面点击事件 防抖
     * @param {Object} ev  $event
     * @param {String} name 执行名称
     * @param {Object} data 传值
     */
    onClickOperate(ev, name, data = {}) {
      _delay(() => {
        switch (name) {
          // 切换 区间
          case 'changeActive':
            this.scrollTop = this.oldScrollTop;
            this.changeActive(data);
            break;
          // 开启 隐藏 空箱
          case 'changeOpen':
            this.changeOpenType(data);
            break;
          // 选择箱子
          case 'select':
            // if (data.item.surplus == 0) {
            //   uni.showToast({
            //     title: '该箱已被抽空，去其他箱盒看看吧',
            //     icon: 'none',
            //     mask: true,
            //   });
            // }
            setTimeout(() => {
              this.selectBox(data);
            }, 1000);

            break;
          // 关闭弹窗
          case 'close':
            this.close(data);
            break;
        }
      });
    },
    // 监听滚动条
    onScroll(e) {
      this.oldScrollTop = e.detail.scrollTop;
    },
    // 滚动到底
    onreachBottom() {},
    // 切换 查看状态
    changeOpenType() {
      this.checkNone = !this.checkNone;
      if (this.checkNone) {
        this.checkNoneClass = 'open';
      } else {
        this.checkNoneClass = 'close';
      }
    },
    //选择箱子
    selectBox(ev) {
      const { item, index } = ev;
      this.$emit('select', { item, index });
      this.close();
    },
    // 切换区间
    changeActive(ev) {
      if (this.active === ev.index) return;
      this.active = ev.index;
      const { value: rows, min: page } = this.tabList[this.active];
      this.$emit('changeActive', ev);
      this.getBoxList({
        page,
        rows,
      }).then((res) => {
        this.scrollTop = 0;
      });
    },

    // 关闭 弹窗
    close() {
      this.$emit('changeBoxListMod', false);
    },

    // 初始化列表
    initList() {
      let list = [];
      if (this.total === 0 || !this.total) return list;
      if (this.total <= this.rows) {
        for (let t = 1; t <= this.total; t++) {
          list.push({
            label: `${t}号箱`,
            min: t,
            max: t,
            value: 1,
            index: t,
          });
        }
        return list;
      }
      let interval = parseInt(this.total / this.rows);
      let remainder = this.total % this.rows;
      for (let i = 1; i <= this.rows; i++) {
        let num = i * interval;
        let first = num - interval + 1;
        let end = num + remainder;
        let obj = {
          label: `${first}-${num}箱`,
          min: first,
          max: num,
          value: interval,
          index: i,
        };
        if (i == this.rows) {
          obj = {
            label: `${first}-${end}箱`,
            min: first,
            max: end,
            value: interval + remainder,
            index: i,
          };
        }
        list.push(obj);
      }
      return list;
    },

    // 首次进入
    firstInitData() {
      if (this.total > this.threshold) {
        let current = this.tabList.find((item) => {
          return item.min <= this.currentIndex && item.max >= this.currentIndex;
        });
        let page = 1;
        let rows = 1;
        if (current) {
          this.active = current.index - 1;
          page = current.min;
          rows = current.value;
        } else {
          this.active = 0;
          rows = this.tabList[0].value;
        }
        this.getBoxList({
          page,
          rows,
        }).then();
      } else {
        this.getBoxList({
          page: 1,
          rows: this.total,
        }).then();
      }
    },

    /**
     * @description 获取箱子列表
     * @param {Object} ev
     */
    getBoxList(ev = {}) {
      let { status = 'init', page = 1, rows = 1 } = ev;
      return new Promise((resolve, reject) => {
        this.$http(
          'v1.yfsboxs',
          {
            id: this.initiallyId,
            page,
            rows,
          },
          '加载中'
        ).then((res) => {
          if (res.code === 1) {
            this.list = res.data;
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },
  },
  /** ---------- */
};
</script>
<style lang="scss" scoped>
.box-list-module {
  --w: 100vw;
  --h: 100vh;
  --vw: 350rpx;
  --vh: 96vh;

  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 100073;
  width: var(--w);
  height: var(--h);

  .popup {
    position: absolute;
    top: 0;
    left: 0;
    width: var(--w);
    height: var(--h);
    background: rgba(0, 0, 0, 0.8);
  }
  .box-module {
    position: absolute;
    bottom: 0;
    left: 0;
    z-index: 10;
    width: var(--vw);
    height: var(--vh);
    background-color: #fff;
    border-radius: 5rpx 5rpx 0 0;
    animation: slide-in-left-q 1s linear 0s 1 normal none;

    .top {
      position: relative;
      display: flex;
      padding: 8rpx 7rpx 7rpx;
      width: 100%;
      .title {
        display: flex;
        align-items: center;
        font-size: 15rpx;
        font-weight: 800;
        color: #000000;
      }
      .close-icon {
        position: absolute;
        top: 24rpx;
        right: 15rpx;
        width: 16rpx;
        height: 9rpx;
      }
    }

    .tabs {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 15rpx;
      padding: 3rpx 15rpx;

      .tab-item {
        padding: 5rpx 10rpx;
        text-align: center;
        min-width: 78rpx;
        border-radius: 3rpx;
        border: 1rpx solid #9456df;
        font-size: 13rpx;
        background: rgba(136, 49, 252, 0.1);
        color: #9456df;
      }
      .tab-item.active {
        background: #9456df;
        border: 1rpx solid #9456df;
        color: #fff;
        font-weight: bold;
      }
    }
  }

  .switch-type.close {
    filter: grayscale(100);
  }
  .switch-type {
    display: flex;
    align-items: center;
    position: relative;
    margin-left: 8rpx;
    padding: 1rpx 2rpx;
    width: 64rpx;
    height: 21rpx;
    border-radius: 20rpx;
    border: 1rpx solid rgba(246, 122, 199, 1);
    font-size: 11rpx;
    font-weight: bold;
    color: #f67ac7;
    overflow: hidden;
    transition: all 0.4s;

    .type-group.close {
      width: 100%;
      .round {
        animation: rotate-in 0.5s linear 0s 1 normal none;
      }
    }
    .type-group.open {
      width: 20rpx;
      .round {
        animation: rotate-over 0.5s linear 0s 1 normal none;
      }
    }
    .type-group {
      position: absolute;
      left: 0;
      top: 0;
      padding: 1rpx 2rpx;
      padding-left: 10rpx;
      height: 100%;
      width: 20rpx;
      color: #ccc;
      background: #fff;
      overflow: hidden;
      transition: width 0.5s;

      text {
        position: absolute;
        left: 8rpx;
        top: 50%;
        width: 34rpx;
        transform: translateY(-50%);
        line-height: 1;
      }
    }

    .round {
      transition: transform 0.5s;
      transform: rotate(0deg);
      position: absolute;
      right: 2rpx;
      top: 1rpx;
      width: 17rpx;
      height: 17rpx;
      border-radius: 50%;
      background-image: linear-gradient(
        75deg,
        rgba(252, 114, 226, 1),
        rgba(225, 145, 110, 1)
      );
    }
    .none {
      width: 100%;
      text-align: right;
      padding-right: 5rpx;
      background-image: linear-gradient(
        45deg,
        rgba(252, 114, 226, 1),
        rgba(225, 145, 110, 1)
      );
      background-clip: text;
      color: transparent;
    }
  }

  .content {
    position: relative;
    padding: 0 15rpx 15rpx;
    width: 100%;
    height: calc(var(--vh) - 90rpx);

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      z-index: 4;
      width: 100%;
      height: 40rpx;
      box-shadow: 0 -14rpx 15rpx #fff inset;
    }
  }
}

@keyframes rotate-in {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(720deg);
  }
}
@keyframes rotate-over {
  0% {
    transform: rotate(720deg);
  }
  100% {
    transform: rotate(0deg);
  }
}
</style>
